<template>
	<view class="main">
		<!-- <tn-popup v-model="voicePopShow" mode="bottom" :maskCloseable="false" :closeBtn="true"> -->
		<view class="voicePopShow" :style="{'bottom':isbottom}">
			<view class="seconds">{{formatTime(timer)}}</view>
			<view class="tishi">最短5秒，最长60秒</view>
			<view class="tishi">为了保障音效建议使用耳机无燥录制</view>
			<view class="operate tn-flex tn-flex-col-center">
				<image src="/static/my/pause1.png" v-if="!pAudioaState" :style="{right:iconReft}" @click="previewPlay"
					class="pause1" mode="">
				</image>
				<image src="/static/my/pause2.png" v-else :style="{right:iconReft}" @click="previewPause" class="pause1"
					mode="">
				</image>
				<image src="/static/my/success.png" :style="{left:iconLeft}" @click="confirm" class="s-icon" mode="">
				</image>
				<image src="https://web.lanmei.co/image/pause.png" v-if="voiceState == 1 || voiceState == 3"
					@click="start" class="start" mode=""></image>
				<image src="/static/my/pause.png" v-else @click="pause" class="start" mode=""></image>
			</view>
			<view class="start-text">{{setVoiceStateTex}}</view>
		</view>
		<view class="mack" @click="close" v-if="isbottom == '0px'"></view>
		<!-- </tn-popup> -->

		<permissionGuide ref="refPermissionGuide" />
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	const recordOptions = {
		duration: 60000,
		sampleRate: 44100,
		numberOfChannels: 1,
		encodeBitRate: 192000,
		format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
	}
	import permision from "@/js_sdk/wa-permission/permission.js"
	import permissionGuide from '@/components/permissionGuide/index.vue'
	import {
		requestPermission
	} from '@/tools/permision.js'
	export default {
		components: {
			permissionGuide
		},
		data() {
			return {
				voicePopShow: false,
				iconLeft: '40rpx',
				iconReft: '40rpx',
				voiceState: 1, // 1 正常未开始状态 2停止录音 3重新录制
				timer: 0,
				jId: '',
				audioUrl: '',
				pAudioaState: false, //预览音频播放状态
				isbottom: '-300px'

			}
		},
		computed: {
			setVoiceStateTex() {
				return this.voiceState == 1 ? '开始录音' : this.voiceState == 2 ? '停止录音' : '重新录制'
			},
			formatTime() {
				return function(time) {
					const minutes = Math.floor(time / 60)
					const seconds = time % 60; // 计算秒数
					return `${String(minutes).padStart(2, '0')}.${String(seconds).padStart(2, '0')}`
				}
			}
		},
		mounted() {
			// 监听录音开始
			recorderManager.onStart((res) => {
				console.log('recorder onStart', res);
				this.startDate()
				this.iconReft = '240rpx'
				this.iconLeft = '240rpx'
				this.voiceState = 2
			})
			// 监听录音停止
			recorderManager.onStop((res) => {
				console.log('recorder stop', res);
				this.audioUrl = res.tempFilePath
				innerAudioContext.src = this.audioUrl
				this.stopTimer()
				this.voiceState = 3
			});
			// 监听录音错误
			recorderManager.onError((res) => {
				console.log('recorder onError');
				console.log(res)
			})

			// 预览音频播放完毕
			innerAudioContext.onEnded(res => {
				this.pAudioaState = false
			})

		},
		methods: {
			async open() {
				const _microphonePermission = await requestPermission("microphone")

				if (_microphonePermission != 1) {
					// 只ios才显示权限引导
					if (this.$isIos) {
						this.$refs.refPermissionGuide.open({
							perName: 'microphone'
						})
					}
					return
				}

				this.isbottom = '0px'
			},
			close() {
				if (this.voiceState == 2) {
					uni.showToast({
						title: "请录音结束后在关闭",
						icon: "none"
					})
				} else {
					this.isbottom = '-300px'
				}
				// this.voicePopShow = false

			},
			// 开始录音
			start() {
				if (this.voiceState == 3) {
					this.timer = 0
					this.audioUrl = ''
				}
				// #ifdef MP-WEIXIN
				this.MPStart()
				// #endif
				// #ifdef APP-PLUS
				this.AppStart()
				// #endif
			},
			// 小程序端
			MPStart() {
				uni.authorize({
					scope: 'scope.record',
					success: () => {
						recorderManager.start(recordOptions)
					},
					fail: () => {
						uni.showToast({
							title: '录音权限暂未开启，请开启',
							icon: 'none',
						})
					}
				})
			},
			// app端
			AppStart() {
				let env = uni.getSystemInfoSync().platform
				if (env == 'android') {
					permision.requestAndroidPermission('android.permission.RECORD_AUDIO').then(res => {
						console.log(res)
						if (res == -1 || res == 0) {
							uni.showToast({
								title: '录音权限暂未开启，请在应用设置中手动打开',
								icon: 'none',
							})
							setTimeout(() => {
								permision.gotoAppPermissionSetting()
							}, 800)

						} else {
							recorderManager.start(recordOptions)
						}
					})

				} else if (env == 'ios') {
					if (permision.judgeIosPermission("record")) {
						recorderManager.start(recordOptions)
					} else {
						uni.showToast({
							title: '您拒绝了录音授权，请在应用设置中手动打开',
							icon: 'none',
						})
					}
				}

			},
			// 停止录音
			pause() {
				if (this.timer < 5) {
					uni.showToast({
						title: "最少录制5秒",
						icon: "none"
					})
					return
				}
				recorderManager.stop()
			},
			// 计时器
			startDate() {
				this.jId = setInterval(() => {
					this.timer++
				}, 1000)
			},
			stopTimer() {
				clearInterval(this.jId); // 清除计时器
			},
			// 播放录制的音频
			previewPlay() {
				if (this.voiceState == 1) {
					uni.showToast({
						title: "您还未录制声音",
						icon: "none"
					})
					return
				}
				if (this.voiceState == 2) {
					uni.showToast({
						title: "请暂停后播放",
						icon: "none"
					})
					return
				}
				innerAudioContext.play()
				this.pAudioaState = true
			},
			previewPause() {
				innerAudioContext.pause()
				this.pAudioaState = false
			},
			// 确认当前录音
			confirm() {
				if (this.voiceState != 3) {

					return
				}
				this.$emit('endRecord', {
					tempFilePath: this.audioUrl,
					duration: this.timer
				})
				this.close()

			}
		}
	}
</script>

<style lang="scss" scoped>
	.mack {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);

	}

	.voicePopShow {
		background-color: #1D1E30;
		height: 546rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 80rpx;
		position: fixed;
		left: 0;
		right: 0;
		z-index: 11;
		transition: bottom 0.5s;

		.seconds {
			font-size: 56rpx;
			font-weight: bold;
			color: #FFB2F9;
			margin-bottom: 16rpx;
		}

		.tishi {
			font-size: 28rpx;
			font-weight: 400;
			color: #EFEFEF;
		}

		.operate {
			margin-top: 32rpx;
			position: relative;

			.pause1 {
				width: 64rpx;
				height: 64rpx;
				position: absolute;
				transition: right .4s linear;
				// right: 40rpx;
			}

			.s-icon {
				width: 64rpx;
				height: 64rpx;
				position: absolute;
				transition: left .4s linear;
				// left: 40rpx;

			}

			.start {
				width: 120rpx;
				height: 120rpx;
				z-index: 10;
			}
		}

		.start-text {
			font-size: 28rpx;
			font-weight: 400;
			color: #EFEFEF;
			margin-top: 16rpx;
		}
	}
</style>